using System.Collections.Generic;
using System.Linq;
using CxRomos.Core.Domain;
using CxRomos.Core.Domain.Entities;
using StructureMap;

namespace CxRomos.Core.DataAccess.Implementation {
    [Pluggable("Default")]
    public class AccountRepository : RepositoryBase, IAccountRepository {
        public Account GetAccountById(int accountId) {
            var account = (from a in Context.Accounts
                           where a.AccountId == accountId
                           select a).SingleOrDefault();

            return account;
        }

        public Account GetAccountByEmail(string email) {
            var account = (from a in Context.Accounts
                           where a.Email == email
                           select a).SingleOrDefault();

            return account;
        }

        public Account GetAccountByUsername(string username) {
            var account = (from a in Context.Accounts
                           where a.Username == username
                           select a).SingleOrDefault();

            return account;
        }

        public void SaveAccount(Account account) {
            BeginTransaction();
            NHibernateSession.SaveOrUpdate(account);
        }

        public void SaveAccount(Account account, Permission permission) {
            BeginTransaction();            
            var ap = new AccountPermission {AccountId = account.AccountId, Permission = permission};
            NHibernateSession.SaveOrUpdate(ap);
        }

        public void DeleteAccount(Account account) {
            BeginTransaction();
            NHibernateSession.Delete(account);
        }

        public void AddPermission(Account account, Permission permission) {
            var ap = new AccountPermission {
                                                AccountId = account.AccountId,
                                                Permission = permission
                                            };

            BeginTransaction();
            NHibernateSession.SaveOrUpdate(ap);
        }

        public List<Account> GetAllAccounts(int pageNumber) {
            IEnumerable<Account> accounts = (from a in Context.Accounts
                        orderby a.Username
                        select a).Skip((pageNumber - 1)*10).Take(10);

            return accounts.ToList();
        }
    }
}